using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Impact.Model.Objects;
using Impact.Infrastructure.Plugins;
using Impact.Web.Foundation;
using System.Collections.Generic;
using Impact.Controllers;
using Impact.Infrastructure.Exceptions;

namespace Impact.Web.Admin
{
    /// <summary>
    /// code-behind for edit plugins page
    /// </summary>
    public partial class EditPlugins : PageBase
    {
        private EditPluginController controller;

        /// <summary>
        /// override of onload to perform startup processing
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            controller = new EditPluginController(this.PageId);

            base.OnLoad(e);

            // run this after base.OnLoad() to override the base class setting
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                ReferringUrl = returnUrl;
            }


        }

        /// <summary>
        /// overridden to handling binding on this page
        /// </summary>
        protected override void Bind()
        {

            title.Text = string.Format("{0} - Plugins", controller.GetPageCaption());

            // populate add plugin dropdown
            addPlugin.DataValueField = "PluginId";
            addPlugin.DataTextField = "Name";
            addPlugin.DataSource = PluginCache.Instance;
            addPlugin.DataBind();

            BindRepeater();
        }

        private void BindRepeater()
        {
            // data for plugin repeater
            this.pluginsRepeater.DataSource = controller.GetPlugins();
            this.pluginsRepeater.DataBind();
        }


        #region Event Handlers

        /// <summary>
        /// event handler for when an item in the plugin repeater is data bound
        /// </summary>
        protected void pluginsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DropDownList location = (DropDownList)e.Item.FindControl("location");
            PagePlugin plugin = (PagePlugin)e.Item.DataItem;
            location.SelectedIndex = plugin.Location - 1;
        }

        /// <summary>
        /// event handler for when the user selects to add a plugin
        /// </summary>
        protected void AddPlugin(object sender, EventArgs e)
        {
            if (addPlugin.SelectedValue.Length == 36) // 36 is standard length of Guid in string form
            {
                Guid pluginId = new Guid(addPlugin.SelectedValue);
                controller.AddPlugin(this.PageId, pluginId);

                BindRepeater();
            }

        }

        /// <summary>
        /// Event handler for when the user changes the location for a plugin
        /// </summary>
        protected void Location_Changed(object sender, EventArgs e)
        {
            DropDownList location = sender as DropDownList;
            RepeaterItem item = (RepeaterItem)location.Parent;

            PagePluginCollection plugins = controller.GetPlugins();
            PagePlugin plugin = plugins[item.ItemIndex];

            plugin.Location = location.SelectedIndex + 1;

            controller.Save(plugin);

            BindRepeater();

        }


        /// <summary>
        /// event handler for when the Ok button is clicked
        /// </summary>
        protected void Ok_Command(object sender, EventArgs e)
        {
            Return();
        }

        /// <summary>
        /// event handler for when the up arrow is clicked, moves the selected item up in the order
        /// </summary>
        protected void Up_Command(object sender, CommandEventArgs e)
        {
            int registrationId = Int32.Parse(e.CommandArgument.ToString());
            controller.DecreaseSequence(registrationId);

            BindRepeater();
        }

        /// <summary>
        /// event handler for when the down arrow is clicked, moves the selected item down in the order
        /// </summary>
        protected void Down_Command(object sender, CommandEventArgs e)
        {
            int registrationId = Int32.Parse(e.CommandArgument.ToString());
            controller.IncreaseSequence(registrationId);

            BindRepeater();
        }

        /// <summary>
        /// event handler for when the user clicks the 'edit parameters' button in the repeater
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Parameter_Command(object sender, CommandEventArgs e)
        {
            Redirect(string.Format("EditPluginParameters.aspx?rid={0}&ReturnUrl={1}", e.CommandArgument.ToString(), Server.UrlEncode(Request.Url.ToString()) ));
        }

        /// <summary>
        /// event handler for when the delete button is clicked
        /// </summary>
        protected void Delete_Command(object sender, CommandEventArgs e)
        {
            int registrationId = Int32.Parse(e.CommandArgument.ToString());
            controller.DeletePlugin(registrationId);

            BindRepeater();
        }

        #endregion

        #region Internal Helpers


        private int PageId
        {
            get
            {
                string pid = Request.QueryString["pid"];
                Check.Require(!string.IsNullOrEmpty(pid), "PID is required on the querystring");
                return Int32.Parse(pid);
            }
        }



        #endregion

    }
}
